<script setup>
import { ref, computed, watch } from 'vue';

// 表单数据
const leaveTypeIndex = ref(0);
const leaveTypeOptions = ref(['病假', '事假', '公假', '其他']);
const startDate = ref('');
const endDate = ref('');
const leaveCampusIndex = ref(0);
const leaveCampusOptions = ref(['否', '是']);
const destinationIndex = ref(0);
const destinationOptions = ref(['本地', '外地']);
const detailAddress = ref('');
const emergencyPhone = ref('');
const leaveReason = ref('');
const attachmentPath = ref('');

// 计算属性：是否显示目的地相关字段
const showDestination = computed(() => {
  return leaveCampusIndex.value === 1; // 1表示"是"出校
});

// 计算属性：请假时长
const leaveDuration = computed(() => {
  if (!startDate.value || !endDate.value) {
    return 0;
  }

  const start = new Date(startDate.value);
  const end = new Date(endDate.value);

  // 计算天数差
  const diffTime = Math.abs(end - start);
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

  return diffDays + 1; // 包含开始和结束日期
});

// 监听开始时间和结束时间的变化，确保结束时间不早于开始时间
watch([startDate, endDate], () => {
  if (startDate.value && endDate.value) {
    const start = new Date(startDate.value);
    const end = new Date(endDate.value);

    if (end < start) {
      endDate.value = startDate.value;
      uni.showToast({
        title: '结束时间不能早于开始时间',
        icon: 'none'
      });
    }
  }
});

// 事件处理函数
const onLeaveTypeChange = (e) => {
  leaveTypeIndex.value = e.detail.value;
};

const onStartTimeChange = (e) => {
  startDate.value = e.detail.value;
};

const onEndTimeChange = (e) => {
  endDate.value = e.detail.value;
};

const onLeaveCampusChange = (e) => {
  leaveCampusIndex.value = e.detail.value;
};

const onDestinationChange = (e) => {
  destinationIndex.value = e.detail.value;
};

// 上传附件
const uploadAttachment = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      const tempFilePath = res.tempFilePaths[0];

      // 这里只是模拟上传，实际项目中需要调用真实的上传接口
      attachmentPath.value = tempFilePath;

    },
    fail: (err) => {
      console.error('选择图片失败:', err);
    }
  });
};

// 删除附件
const deleteAttachment = () => {
  attachmentPath.value = '';
};

// 表单验证
const validateForm = () => {
  // if (leaveTypeIndex.value === 0) {
  //   uni.showToast({ title: '请选择请假类型', icon: 'none' });
  //   return false;
  // }
  //制作的过程中出现了bug，默认选项被判断为无效选项，检查之后发现不需要这些

  if (!startDate.value) {
    uni.showToast({ title: '请选择开始时间', icon: 'none' });
    return false;
  }

  if (!endDate.value) {
    uni.showToast({ title: '请选择结束时间', icon: 'none' });
    return false;
  }

  // if (leaveCampusIndex.value === 0) {
  //   uni.showToast({ title: '请选择是否出校', icon: 'none' });
  //   return false;
  // }
  //同上

  // if (showDestination.value && destinationIndex.value === 0) {
  //   uni.showToast({ title: '请选择目的地', icon: 'none' });
  //   return false;
  // }
  //同上

  if (showDestination.value && !detailAddress.value) {
    uni.showToast({ title: '请填写目的地详细地址', icon: 'none' });
    return false;
  }

  if (!emergencyPhone.value || emergencyPhone.value.length !== 11) {
    uni.showToast({ title: '请填写正确的紧急联系电话', icon: 'none' });
    return false;
  }

  if (!leaveReason.value) {
    uni.showToast({ title: '请填写请假理由', icon: 'none' });
    return false;
  }

  if (leaveTypeIndex.value === 0 && !attachmentPath.value) { // 病假需要附件
    uni.showToast({ title: '病假请上传医院证明', icon: 'none' });
    return false;
  }

  return true;
};

// 提交请假申请
const submitLeaveApplication = () => {
  if (!validateForm()) {
    return;
  }

  //获取当前时间作为申请时间
  const now = new Date()
  const applyTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;

  // 构建提交数据
  const formData = {
    // leaveType: leaveTypeOptions.value[leaveTypeIndex.value],
    // startDate: startDate.value,
    // endDate: endDate.value,
    //因为要将数据传入myLeave所以作出修改
    id:Date.now().toString(),//生成唯一id
    applyTime:applyTime,
    type:leaveTypeOptions.value[leaveTypeIndex.value],
    startTime:startDate.value,
    endTime:endDate.value,
    leaveDuration: leaveDuration.value,
    leaveCampus: leaveCampusOptions.value[leaveCampusIndex.value],
    destination: showDestination.value ? destinationOptions.value[destinationIndex.value] : '',
    detailAddress: detailAddress.value,
    emergencyPhone: emergencyPhone.value,
    leaveReason: leaveReason.value,
    attachmentPath: attachmentPath.value,
    status:'pending'//默认状态为审批中
  };

  // 保存到本地储存
  const existingRecords = uni.getStorageSync('leaveRecords') || []//若不存在初始化为空数组
  existingRecords.push(formData)
  uni.setStorageSync('leaveRecords',existingRecords)

  //为了计数写的一个方法
  const Counter = function(record){
    return record.status === 'pending' ||
        record.status === 'approved' ||
        record.status === 'rejected' ||
        record.status === 'waitingCancel';
  }
  //同上
  const WaitCounter = function (record){
    return record.status ==="waitingCancel"
  }


  //更新“我的请假”计数
  const myLeaveCount = existingRecords.filter(Counter).length
  uni.setStorageSync('myLeaveCount',myLeaveCount)

  //更新“待销假”计数
  const waitingCancelCount = existingRecords.filter(WaitCounter).length
  uni.setStorageSync('waitingCancelCount',waitingCancelCount)


  console.info('提交的数据:', formData);

  uni.showToast({
    title: '提交成功',
    icon: 'success'
  });

  // 提交成功后返回上一页
  setTimeout(() => {
    uni.navigateBack();
  }, 1500);

};
</script>

<template>
  <view class="container">
    <!-- 表单容器 -->
    <view class="form-container">
      <!-- 请假类型 -->
      <view class="form-item">
        <text class="form-label">请假类型</text>
        <picker @change="onLeaveTypeChange" :value="leaveTypeIndex" :range="leaveTypeOptions">
          <view class="form-picker">
            {{ leaveTypeOptions[leaveTypeIndex] || '请选择请假类型' }}
            <text class="arrow-icon">▼</text>
          </view>
        </picker>
      </view>

      <!-- 开始时间 -->
      <view class="form-item">
        <text class="form-label">开始时间</text>
        <picker mode="date" @change="onStartTimeChange" :value="startDate">
          <view class="form-picker">
            {{ startDate || '请选择开始时间' }}
            <text class="arrow-icon">▼</text>
          </view>
        </picker>
      </view>

      <!-- 结束时间 -->
      <view class="form-item">
        <text class="form-label">结束时间</text>
        <picker mode="date" @change="onEndTimeChange" :value="endDate">
          <view class="form-picker">
            {{ endDate || '请选择结束时间' }}
            <text class="arrow-icon">▼</text>
          </view>
        </picker>
      </view>

      <!-- 请假时长 -->
      <view class="form-item">
        <text class="form-label">你的请假时长为：</text>
        <view class="duration-display">
          {{ leaveDuration }}天
        </view>
      </view>

      <!-- 是否出校 -->
      <view class="form-item">
        <text class="form-label">是否出校</text>
        <picker @change="onLeaveCampusChange" :value="leaveCampusIndex" :range="leaveCampusOptions">
          <view class="form-picker">
            {{ leaveCampusOptions[leaveCampusIndex] || '请选择是否出校' }}
            <text class="arrow-icon">▼</text>
          </view>
        </picker>
      </view>

      <!-- 目的地 -->
      <view class="form-item" v-if="showDestination">
        <text class="form-label">目的地</text>
        <picker @change="onDestinationChange" :value="destinationIndex" :range="destinationOptions">
          <view class="form-picker">
            {{ destinationOptions[destinationIndex] || '请选择目的地' }}
            <text class="arrow-icon">▼</text>
          </view>
        </picker>
      </view>

      <!-- 目的地详细地址 -->
      <view class="form-item" v-if="showDestination">
        <text class="form-label">目的地详细地址</text>
        <input
            class="form-input"
            placeholder="请详细填写地址信息，如需小区名、门牌号等"
            v-model="detailAddress"
        />
      </view>

      <!-- 紧急联系电话 -->
      <view class="form-item">
        <text class="form-label">紧急联系电话</text>
        <input
            class="form-input"
            type="number"
            placeholder="请输入紧急人联系电话"
            v-model="emergencyPhone"
            maxlength="11"
        />
      </view>

      <!-- 请假理由 -->
      <view class="form-item">
        <text class="form-label">请假理由</text>
        <textarea
            class="form-textarea"
            placeholder="请详细填写你的请假理由，以便辅导员快速通过审核。字数不超过100字"
            v-model="leaveReason"
            maxlength="100"
            show-confirm-bar="false"
        />
        <text class="word-count">{{ leaveReason.length }}/100</text>
      </view>

      <!-- 附件 -->
      <view class="form-item">
        <text class="form-label">附件（非必填）</text>
        <text class="form-hint">注：病假的同学请上传医院证明，其余请假同学请上传其他证明材料。图片单张大小不超过2M</text>
        <view class="attachment-container">
          <view class="upload-btn" @click="uploadAttachment">
            <text class="upload-icon">+</text>
            <text class="upload-text">添加附件</text>
          </view>
          <!-- 已上传附件预览 -->
          <view class="attachment-preview" v-if="attachmentPath">
            <image :src="attachmentPath" mode="aspectFill" class="preview-image"></image>
            <view class="delete-icon" @click="deleteAttachment">×</view>
          </view>
        </view>
      </view>

      <!-- 提交按钮 -->
      <button class="submit-btn" @click="submitLeaveApplication">提交</button>
    </view>
  </view>
</template>

<style scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 40rpx;
}

.form-container {
  padding: 30rpx;
  background-color: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.form-item {
  margin-bottom: 40rpx;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 16rpx;
  font-weight: 500;
}

.form-hint {
  display: block;
  font-size: 24rpx;
  color: #999;
  margin-bottom: 16rpx;
  line-height: 1.4;
}

.form-picker {
  height: 80rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24rpx;
  background-color: #fff;
  color: #666;
  font-size: 28rpx;
}

.arrow-icon {
  color: #999;
  font-size: 20rpx;
}

.form-input {
  height: 80rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  padding: 0 24rpx;
  font-size: 28rpx;
  color: #333;
}

.form-textarea {
  width: 100%;
  height: 200rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 28rpx;
  color: #333;
  box-sizing: border-box;
  resize: none;
}

.word-count {
  display: block;
  text-align: right;
  font-size: 24rpx;
  color: #999;
  margin-top: 8rpx;
}

.duration-display {
  height: 80rpx;
  display: flex;
  align-items: center;
  color: #2f5496;
  font-size: 32rpx;
  font-weight: 500;
}

.attachment-container {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 20rpx;
}

.upload-btn {
  width: 160rpx;
  height: 160rpx;
  border: 1rpx dashed #e0e0e0;
  border-radius: 8rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
  color: #999;
}

.upload-icon {
  font-size: 48rpx;
  margin-bottom: 8rpx;
}

.upload-text {
  font-size: 24rpx;
}

.attachment-preview {
  width: 160rpx;
  height: 160rpx;
  border-radius: 8rpx;
  overflow: hidden;
  position: relative;
}

.preview-image {
  width: 100%;
  height: 100%;
}

.delete-icon {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36rpx;
  font-weight: bold;
}

.submit-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  background-color: #2f5496;
  color: #fff;
  font-size: 32rpx;
  font-weight: 500;
  border-radius: 45rpx;
  margin-top: 20rpx;
}

.submit-btn:active {
  background-color: #244078;
}
</style>